<template>
  <div class="gap-col-16 mt-4">
    <DateRangeInput v-model="dateRange"></DateRangeInput>
    <v-row class="px-1 py-2">
      <v-col
        v-for="(card, index) in totalPerformanceCards"
        :key="`performance-card-${index}`"
        cols="6"
        class="px-2 py-2"
      >
        <EarnPerformCard :label="card.label" :text="card.text"></EarnPerformCard>
      </v-col>
    </v-row>
  </div>
</template>
<script setup>
import EarnPerformCard from '@/components/mine/EarnPerformCard.vue'
import DateRangeInput from '@/components/form/DateRangeInput.vue'
import { onActivated, onMounted, ref, shallowRef, watch } from 'vue'
import API from '@/http'
import { useEarnStore } from '@/store/earn'
import { storeToRefs } from 'pinia'
import { addDays, toFixedString } from '@/utils/string-helper'
import { VRow, VCol } from 'vuetify/components'

const earnStore = useEarnStore()
const { isTrigger } = storeToRefs(earnStore)

watch(isTrigger, (val) => {
  if (!val) return
  fetch()
})

const dateRange = shallowRef([addDays(-7), new Date()])

watch(dateRange, (newVal) => {
  fetch(newVal[0], newVal[1])
})

const totalPerformanceCards = ref([
  { label: 'label.earnIndex.accounts', text: '123', key: 'visitor_num' },
  { label: 'label.earnIndex.dailyAccounts', text: '123', key: 'visitor_avg_num' },
  { label: 'label.earnIndex.subscribers', text: '123', key: 'subscribe_num' },
  { label: 'label.earnIndex.desubscriber', text: '123', key: 'unsubscribe_num' },
  { label: 'label.earnIndex.watches', text: '123', key: 'view_num' },
  { label: 'label.earnIndex.clickRate', text: '123', key: 'click_rate' },
  { label: 'label.earnIndex.periodProfit', text: '123', key: 'in_come' },
  { label: 'label.earnIndex.completionTimes', text: '123', key: 'play_complete_num' },
  { label: 'label.earnIndex.broadcastRevenueIncentive', text: '123', key: 'in_come_play_complete' },
])

onMounted(() => fetch(dateRange.value[0], dateRange.value[1]))
onActivated(() => fetch(dateRange.value[0], dateRange.value[1]))

const fetch = async (start = null, end = null) => {
  try {
    const data = {}
    if (start) data.start = start
    if (end) data.end = end
    const response = await API.Earn.income({ data })
    console.log(response,'response');
    
    Object.entries(response).forEach(([key, value]) => {
      const card = totalPerformanceCards.value.find((card) => card.key === key)
      if (!card) return

      if (key === 'in_come'||key === 'in_come_play_complete') {
        card.text = '$' + toFixedString(value, 2)
        return
      }
      card.text = value.toString()
    })
  } catch (e) {
    console.error(e)
  }
}
</script>
<style scoped lang="scss">
::v-deep(.v-row) {
  margin-bottom: 4rem;
}
</style>
